<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-title">
        <h2>旅游信息管理系统</h2>
        <p>Tourism Information Management System</p>
      </div>
      <el-form :model="loginForm" :rules="rules" ref="loginFormRef" class="login-form">
        <el-form-item prop="username">
          <el-input 
            v-model="loginForm.username"
            placeholder="请输入用户名"
            prefix-icon="User"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password" 
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            show-password
          />
        </el-form-item>
        <el-form-item prop="code">
          <div class="captcha-container" style="display: flex; align-items: center;">
            <el-input
              v-model="loginForm.code"
              placeholder="请输入验证码"
              style="width: 200px;"
            />
            <img :src="captchaUrl" alt="验证码" style="height: 40px; width: 120px; margin-left: 10px; cursor: pointer;" @click="getCaptchaImg" />
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="login-btn" @click="handleLogin">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { adminAPI } from '@/utils/api'

const router = useRouter()
const loginFormRef = ref(null)

const loginForm = reactive({
  username: '',
  password: '',
  code: ''
})

const captchaUrl = ref('')

onMounted(() => {
  getCaptchaImg()
})

const getCaptchaImg =  () => {
  adminAPI.getCaptcha().then(res => {
     // 将 ArrayBuffer 转换为 Base64 格式
    const base64Image = arrayBufferToBase64(res.data);
          // 设置图片的 URL（Base64 格式）
    captchaUrl.value = `data:image/png;base64,${base64Image}`;
  }).catch(err => {
    ElMessage({
      message: '获取验证码失败！请重试！',
      type: 'error',
    })
  })
}

// 将 ArrayBuffer 转换为 Base64 字符串的函数
const arrayBufferToBase64 = (buffer) => {
  let binary = '';
  const bytes = new Uint8Array(buffer);
  const len = bytes.byteLength;
  for (let i = 0; i < len; i++) {
    binary += String.fromCharCode(bytes[i]);
  }
  return window.btoa(binary); // 使用 btoa() 转换为 Base64
};

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { 
      len: 5,  // 限制验证码的长度为 5
      message: '验证码长度必须为5位',
      trigger: 'blur'
    }
  ]
}

const handleLogin = () => {
  loginFormRef.value.validate((valid) => {
    if (valid) {
        adminAPI.login(loginForm).then(res => {
            if(res.data.code === 200) {
                ElMessage.success('登录成功！')
                const user = res.data.data;
                //保存用户信息到sessionStorage
                sessionStorage.setItem('admin',JSON.stringify(user))
                router.push('/home')
            }else{
                ElMessage.error(res.data.message)
                getCaptchaImg()
            }
        }).catch(err => {
            ElMessage.error('登录失败,请重试')
        })
    }
  })
}
</script>

<style scoped>
.login-container {
  height: 100vh;
  background: linear-gradient(135deg, #1890ff, #36cfc9);
  display: flex;
  justify-content: center;
  align-items: center;
}

.login-box {
  width: 400px;
  padding: 40px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.login-title {
  text-align: center;
  margin-bottom: 30px;
}

.login-title h2 {
  color: #303133;
  margin: 0;
  font-size: 24px;
}

.login-title p {
  color: #909399;
  margin: 10px 0 0;
  font-size: 14px;
}

.login-form {
  margin-top: 30px;
}

.login-btn {
  width: 100%;
  padding: 12px 0;
}

:deep(.el-input__wrapper) {
  padding: 8px 11px;
}

:deep(.el-button) {
  font-size: 16px;
}
</style>

